package com.chenfan.infra.autoconfiguration;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.chenfan.infra.vo.UserVO;
import com.chenfan.infra.context.TenantContextHolder;
import com.chenfan.infra.context.UserContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;

/**
 * @author K
 * @date 2022/4/22 11:47 AM
 */
@ConditionalOnProperty(
        prefix = "tenant.plugin",
        name = {"enabled"},
        havingValue = "true",
        matchIfMissing = false
)
@Configuration
public class TenantAutoConfiguration {

    @Value("${tenant.plugin.ignore.tables:}")
    private List<String> ignoreTableProperties;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                // 前端传递过来的参数, 设置到对应的参数中
                UserVO user = UserContextHolder.getUserVo();
                if (Objects.nonNull(user)) {
                    return new LongValue(user.getTenantId());
                }
                // 如果不是从前端传递过来的说明是服务之间传递. 服务之间传递需要啊从上下文中直接获取
                Long tenantId = TenantContextHolder.getTenantId();
                return Objects.nonNull(tenantId) ? new LongValue(tenantId) : new LongValue(-1);
            }

            @Override
            public boolean ignoreTable(String tableName) {
                return ignoreTableProperties.contains(tableName);
            }
        }));
        return mybatisPlusInterceptor;
    }
}
